<template>
  <div class="container">
    <div class="boxWrap">
      <!-- 头部 -->
      <loginHeader></loginHeader>
      <!-- 注册表单 -->
      <div class="mainBox registerMainBox" v-show="isRegister">
        <el-row class="reminder">
          <i class="el-icon-warning"></i>
          项目用户请先联系所属企业单位开通项目账号后再通过【企业平台】登入系统
        </el-row>
        <el-row class="formTop">
          <div class="loginLink">
            <span>已有企业账号，</span>
            <span @click="skipLogin" class="toLogin">立即登录</span>
          </div>
          <div class="applyTitle">申请企业账号</div>
        </el-row>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="ruleForm"
          status-icon
          aria-autocomplete="false"
          label-width="150px"
        >
          <el-form-item label="单位类型：">
            <span v-if="companyType === '0'">企业</span>
            <span v-if="companyType === '5'">事业单位</span>
            <span v-if="companyType === '10'">其他</span>
            <span v-if="companyType === '15'">个体工商户</span>
            <el-link
              type="primary"
              @click="toRegister()"
              style="vertical-align: 0; margin-left: 10px"
              >修改</el-link
            >
          </el-form-item>
          <el-form-item
            label="企业类型："
            prop="companyType"
            v-if="companyType === '0'"
          >
            <el-select
              v-model.trim="ruleForm.companyType"
              clearable
              filterable
              placeholder="请选择企业类型"
            >
              <el-option
                v-for="item in companyTypeArr"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称：" prop="companyName">
            <el-input
              v-model.trim="ruleForm.companyName"
              @change="validUsccAndCompany(ruleForm.companyName, ruleForm.uscc)"
              placeholder="输入企业、政府或组织名称"
              clearable
              @blur="ruleForm.companyName = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="统一社会信用代码：" prop="uscc">
            <el-input
              v-model.trim="ruleForm.uscc"
              @change="validUsccAndCompany(ruleForm.companyName, ruleForm.uscc)"
              placeholder="输入统一社会信用代码、仔细核对、请勿填错"
              clearable
              @blur="ruleForm.uscc = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属行业：" prop="industry">
            <el-cascader
              ref="industry"
              class="industrySelect"
              v-model="ruleForm.industry"
              :options="industryOptions"
              filterable
              @change="getIndustry"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="注册登记地区：" prop="belong" class="radioBox">
            <el-radio-group v-model="ruleForm.belong" @change="changeBelong">
              <el-radio label="1">本地</el-radio>
              <el-radio label="2">外地</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="regAddress">
            <el-cascader
              ref="regAreas"
              class="areasSelect"
              :key="isShowRegArea"
              v-model="ruleForm.regAddress"
              :options="regAreasOptions"
              @change="handerChange"
              clearable
              filterable
              placeholder="请选择单位登记地区"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="经营地区"
            prop="manageAddress"
            v-if="ruleForm.belong === '2'"
          >
            <el-cascader
              ref="manageAreas"
              class="areasSelect"
              :key="isShowManaArea"
              v-model="ruleForm.manageAddress"
              :options="areasOptions"
              clearable
              filterable
              placeholder="请选择企业在本地经营场所地址"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="经营地区：" prop="address" v-else>
            <el-input
              v-model.trim="ruleForm.address"
              placeholder="选择单位在本地经营场所地区"
              disabled
              @blur="ruleForm.address = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="密保手机号：" prop="phone">
            <el-input
              v-model.trim="ruleForm.phone"
              placeholder="用于接收审核结果和后期账号安全设置"
              clearable
              @blur="ruleForm.phone = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="短信验证码：" prop="vscode" class="vscodeInput">
            <el-input
              v-model.trim="ruleForm.vscode"
              placeholder="输入短信验证码"
              clearable
              @blur="ruleForm.vscode = changeValue($event)"
            ></el-input>
            <el-button
              size="medium"
              class="vscodeBtn fontBorderTheme fontColorTheme"
              v-show="!isCount"
              @click="getVscode()"
              :disabled="noTel"
              >获取验证码</el-button
            >
            <el-button
              type="info"
              plain
              size="medium"
              round
              v-show="isCount"
              disabled
              >{{ countDownTime }}s后重新获取</el-button
            >
          </el-form-item>
          <!-- 1.企业及个体工商户  3张企业营业执照，身份证正反面  2.事业单位/其他显示一张登记证书 -->
          <template v-if="companyType === '0' || companyType === '15'">
            <el-form-item label="认证资料：" prop="fileImg" class="imgLabel">
              <ul class="imgBoxs clearfix">
                <li class="imgBox">
                  <div class="imgTopBox">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="点击上传图片"
                      placement="bottom"
                    >
                      <form class="uploadBtn" id="licenseForm">
                        <input
                          type="file"
                          name="file"
                          id="licenseFile"
                          accept="image/png, image/jpeg, image/jpg"
                          @change="
                            uploadImg(
                              'licenseFile',
                              0,
                              'licenseForm',
                              'LICENSE'
                            )
                          "
                        />
                        <i class="el-icon-plus"></i>
                        <img :src="file[0].imgSrc" v-show="file[0].isShow" />
                      </form>
                    </el-tooltip>
                    <!-- <div class="imgName">企业营业执照</div> -->
                    <div class="imgName">
                      {{ companyType === '0' ? '企业营业执照' : '营业执照' }}
                    </div>
                  </div>
                  <el-button type="text" @click="licenseDialog = true"
                    >示例图</el-button
                  >
                </li>
                <li class="imgBox">
                  <div class="imgTopBox">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="点击上传图片"
                      placement="bottom"
                    >
                      <form class="uploadBtn" id="idcardForm1">
                        <input
                          type="file"
                          name="file"
                          id="idcardFront"
                          accept="image/png, image/jpeg, image/jpg"
                          @change="
                            uploadImg(
                              'idcardFront',
                              1,
                              'idcardForm1',
                              'IDCARDFRONT'
                            )
                          "
                        />
                        <i class="el-icon-plus"></i>
                        <img :src="file[1].imgSrc" v-show="file[1].isShow" />
                      </form>
                    </el-tooltip>
                    <!-- <div class="imgName">法人身份证正面</div> -->
                    <div class="imgName">
                      {{
                        companyType === '0'
                          ? '法人身份证正面'
                          : '经营者身份证正面'
                      }}
                    </div>
                  </div>
                  <el-button type="text" @click="idcardDialogOne = true"
                    >示例图</el-button
                  >
                </li>
                <li class="imgBox">
                  <div class="imgTopBox">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="点击上传图片"
                      placement="bottom"
                    >
                      <form class="uploadBtn" id="idcardForm2">
                        <input
                          type="file"
                          name="file"
                          id="idcardBack"
                          accept="image/png, image/jpeg, image/jpg"
                          @change="
                            uploadImg(
                              'idcardBack',
                              2,
                              'idcardForm2',
                              'IDCARDBACK'
                            )
                          "
                        />
                        <i class="el-icon-plus"></i>
                        <img :src="file[2].imgSrc" v-show="file[2].isShow" />
                      </form>
                    </el-tooltip>
                    <!-- <div class="imgName">法人身份证反面</div> -->
                    <div class="imgName">
                      {{
                        companyType === '0'
                          ? '法人身份证反面'
                          : '经营者身份证反面'
                      }}
                    </div>
                  </div>
                  <el-button type="text" @click="idcardDialogTwo = true"
                    >示例图</el-button
                  >
                </li>
              </ul>
              <div class="imgRemind">{{ imgRemind }}</div>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="认证资料：" prop="fileImg" class="imgLabel">
              <ul class="imgBoxs clearfix">
                <li class="imgBox">
                  <div class="imgTopBox">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="点击上传图片"
                      placement="bottom"
                    >
                      <form class="uploadBtn" id="licenseForm">
                        <input
                          type="file"
                          name="file"
                          id="licenseFile"
                          accept="image/png, image/jpeg, image/jpg"
                          @change="
                            uploadImg(
                              'licenseFile',
                              0,
                              'licenseForm',
                              'LICENSE'
                            )
                          "
                        />
                        <i class="el-icon-plus"></i>
                        <img :src="file[0].imgSrc" v-show="file[0].isShow" />
                      </form>
                    </el-tooltip>
                    <div class="imgName">单位登记证书</div>
                  </div>
                </li>
                <li>
                  <p style="font-size: 14px; color: #999; line-height: 24px">
                    上传一张带有
                    <span style="color: #e02020">统一社会信用代码</span
                    >的单位登记证书照片，照片所有信息需清晰可见，内容真实可见，不得做任何修改
                  </p>
                  <el-button type="text" @click="registrationDialog = true"
                    >示例图</el-button
                  >
                </li>
              </ul>
              <div class="imgRemind">{{ imgRemind }}</div>
            </el-form-item>
          </template>
          <el-form-item label="" class="contarctBorderBottom">
            <el-checkbox v-model="boxChecked"></el-checkbox>
            我已阅读并同意
            <span class="contract" @click="toRegistration()"
              >《用户注册协议》</span
            >
            和
            <span class="contract" @click="toCreditcommitment()"
              >《信用承诺》</span
            >
          </el-form-item>
          <el-form-item
            label=""
            prop=""
            style="text-align: left; margin-top: 20px"
          >
            <el-button
              v-show="boxChecked"
              type="primary"
              size="medium"
              class="submitBtn registerBtn saveBtn"
              @click="submitForm('ruleForm')"
              :loading="isSubmit"
              >提交申请</el-button
            >
            <el-button
              v-show="!boxChecked"
              type="info"
              disabled
              size="medium"
              class="submitBtn registerBtn"
              >提交申请</el-button
            >
          </el-form-item>
        </el-form>
        <div class="contarctTopBorder"></div>
      </div>
      <!-- 注册完成 -->
      <div class="mainBox registered" v-show="!isRegister">
        <img src="../../../static/img/success.png" alt />
        <div class="suceesRemind">账号申请提交成功</div>
        <div class="messageRemind">
          审核需要1-3个工作日, 审核结果将发送到企业密保手机号
          <span>{{ ruleForm.phone }}</span
          >，请您留意查收
        </div>
        <el-button size="medium" class="submitBtn" @click="skipLogin"
          >返回登录</el-button
        >
      </div>
    </div>
    <el-dialog
      title="营业执照示例图"
      :visible.sync="licenseDialog"
      width="500px;"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/license.jpg" width="400px;" />
    </el-dialog>
    <el-dialog
      title="身份证正面示例图"
      :visible.sync="idcardDialogOne"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/idcard2.jpg" width="400px;" />
    </el-dialog>
    <el-dialog
      title="身份证反面示例图"
      :visible.sync="idcardDialogTwo"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/idcard1.jpg" width="400px;" />
    </el-dialog>
    <el-dialog
      title="单位登记书示例图"
      :visible.sync="registrationDialog"
      width="700px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img
        src="../../../static/img/register/unitRegistration.png"
        width="600px;"
      />
    </el-dialog>
  </div>
</template>

<script>
import jqFrom from '../../kits/jquery.form'
import common from '../../kits/common'
import loginHeader from '@/components/publicCom/loginHeader'

export default {
  name: 'registerNext',
  components: {
    loginHeader,
  },
  data() {
    //验证企业名称
    var validateName = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('企业名称不能为空'))
      } else {
        if (value.length > 100) {
          callback(new Error('企业名称不能超过100个字符'))
        } else {
          if (this.ruleForm.uscc !== '') {
            this.$refs.ruleForm.validateField('uscc')
          }
          callback()
        }
      }
    }
    //验证uscc
    var validateUscc = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('统一社会信用代码不能为空'))
      } else {
        var regUscc = /^[0-9A-Z]{2}[0-9]{6}[0-9A-Z]{10}$/
        if (!regUscc.test(value)) {
          callback(new Error('统一社会信用代码格式不正确'))
        } else {
          callback()
        }
      }
    }
    //验证手机号码
    var validatePhone = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          this.noTel = false
        }
        callback()
      }
    }
    //验证验证码
    var validateVscode = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('验证码不能为空'))
      } else {
        this.axios({
          method: 'post',
          url: 'api-bs/message/base/checkvc',
          data: {
            tel: this.ruleForm.phone.replace(/\s+/g, ''),
            vc: value,
          },
        }).then(
          (res) => {
            if (!res.data.hasError) {
              callback()
            } else {
              callback(new Error(res.data.errorMsg))
            }
          },
          (response) => {
            callback(new Error('验证失败'))
          }
        )
      }
    }
    return {
      bg: require('../../../static/img/login/loginBb.png'), //背景图
      isRegister: true, //注册开始
      noTel: true,
      isSubmit: false, //提交按钮禁止点击
      isCount: false, //是否在倒计时
      countDownTime: 60 /*倒计时 计数器*/,
      licenseDialog: false, //营业执照示例图
      idcardDialogOne: false, //身份证示例图
      idcardDialogTwo: false, //身份证示例图
      registrationDialog: false, //单位登记书示例图
      isShowRegArea: 0,
      isShowManaArea: 0,
      industryOptions: [], //行业数据
      outAreasOptions: [], //省外省市
      neiAreasOptions: [], //内蒙省市
      areasOptions: [], //经营地址
      regAreasOptions: [], //注册地址
      regAreas: {
        regAreaId: '', //注册地址全id
      },
      manageAreas: {
        bizAreaId: '', //经营地址全id
      },
      rules: {
        companyName: [
          { required: true, validator: validateName, trigger: 'blur' },
        ],
        uscc: [
          {
            required: true,
            validator: validateUscc,
            trigger: 'change',
          },
        ],
        industry: [
          { required: true, message: '请选择行业', trigger: 'change' },
        ],
        belong: [
          {
            required: true,
            message: '请选择企业归属',
            trigger: 'change',
          },
        ],
        regAddress: [
          {
            required: true,
            message: '请选择注册地址',
            trigger: 'change',
          },
        ],
        manageAddress: [
          {
            required: true,
            message: '请输入经营地址',
            trigger: 'change',
          },
        ],
        companyType: [
          {
            required: true,
            message: '请选择企业类型',
            trigger: 'change',
          },
        ],
        address: [
          {
            required: true,
            message: '请输入经营地址',
            trigger: 'change',
          },
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur',
          },
        ],
        vscode: [
          {
            required: true,
            validator: validateVscode,
            trigger: 'blur',
          },
        ],
      },
      ruleForm: {
        companyName: '',
        uscc: '',
        industry: '',
        belong: '1',
        regAreaId: [],
        bizAreaId: [], //本省经营地址
        manageAddress: [], //外省经营地址
        regAddress: [],
        address: '',
        phone: '',
        vscode: '',
        companyType: '',
      },
      file: [
        {
          //上传图片
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'LICENSE', //新文件名(营业执照)
          fileSize: '', //文件大小
          // fileType: "BUSINESS_LICENSE", //文件类型
          fileType: 'BUSINESS_LICENSE', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
        {
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'IDCARDFRONT', //新文件名(身份证)
          fileSize: '', //文件大小
          fileType: 'BOSS_IDCARD_FRONT', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
        {
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'IDCARDBACK', //新文件名(身份证)
          fileSize: '', //文件大小
          fileType: 'BOSS_IDCARD_BACK', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
      ],
      companyTypeArr: [], //企业类型
      imgRemind: '', //图片上传不完整的提示
      companyType: '', //0企业单位   5事业单位  10其他
      boxChecked: false,
    }
  },
  mounted() {
    //获取行业
    this.selectIndustry()
    //获取内蒙省市
    this.selectNeiAreas()
    //获取全国省市除内蒙
    this.selectOutAreas()
    this.companyType = this.$route.query.companyType
    //只有单位登记证书时候(事业单位 和 其他)
    if (this.companyType === '5' || this.companyType === '10') {
      this.file[0].fileType = 'AFFILIATED_CERTIFICATE'
    }
  },
  async created() {
    await this.getTypeList()
  },
  methods: {
    // 字典
    getTypeList() {
      return this.axios({
        method: 'get',
        params: {
          type: 'NC_COMPANY_TYPE',
        },
        url: 'api-c/companyaudit/expand/getcompanytype',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.companyTypeArr = response.data.result
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    //跳转登录
    skipLogin() {
      if (this.isCzUser()) {
        this.$router.replace({
          path: '#/login/loginNextCz',
          name: 'loginNextCz',
          query: {
            type: 'QY',
          },
        })
      } else if (this.isEsUser()) {
        this.$router.replace({
          path: '#/login/loginNext',
          name: 'loginNext',
          query: {
            type: 'XM',
          },
        })
      } else {
        this.$router.replace({
          path: '#/login/loginNext',
          name: 'loginNext',
          query: {
            type: 'QY',
          },
        })
      }
    },
    //改变企业归属
    changeBelong(value) {
      //（本省：1，外省：2）
      if (value === '1') {
        ++this.isShowRegArea
        this.regAreasOptions = this.neiAreasOptions
        this.ruleForm.address = ''
        this.$refs.ruleForm.validateField('address', (Error) => {})
      } else {
        ++this.isShowRegArea
        ++this.isShowManaArea
        this.regAreasOptions = this.outAreasOptions
        this.ruleForm.manageAddress = []
        this.$refs.ruleForm.validateField('manageAddress', (Error) => {})
      }
      this.ruleForm.regAddress = []
      this.$refs.ruleForm.validateField('regAddress', (Error) => {})
    },
    //请求行业
    selectIndustry() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-bs/industry/base/detailbyindustryid',
      })
        .then((res) => {
          vm.industryOptions = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    //获取省外省市
    selectOutAreas() {
      let vm = this
      //（本省：1，外省：2）
      vm.axios({
        method: 'post',
        url: 'api-bs/areadic/base/areas',
        data: {
          belongs: 2,
          areaId: this.$store.state.areaInfoArr.areaId,
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            vm.outAreasOptions = res.data.result
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取区域数据失败',
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取区域数据失败',
            type: 'error',
          })
        })
    },
    //获取内蒙省市
    selectNeiAreas() {
      let vm = this
      //（本省：1，外省：2）
      vm.axios({
        method: 'post',
        url: 'api-bs/areadic/base/areas',
        data: {
          belongs: 1,
          areaId: this.$store.state.areaInfoArr.areaId,
        },
      })
        .then(
          (res) => {
            ++vm.isShowRegArea
            ++vm.isShowManaArea
            //内蒙省市
            if (!res.data.hasError) {
              vm.neiAreasOptions = res.data.result
              vm.regAreasOptions = res.data.result
              vm.areasOptions = res.data.result
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: '获取区域数据失败',
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取区域数据失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //发送验证码倒计时
    countDown() {
      let vm = this
      //开启倒计时
      vm.isCount = true
      var auth_timetimer = setInterval(() => {
        vm.countDownTime--
        if (vm.countDownTime <= 0) {
          vm.isCount = false
          clearInterval(auth_timetimer)
        }
      }, 1000)
    },
    //发送验证码
    sendVscode() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-bs/message/base/sendvc',
        data: {
          tel: vm.ruleForm.phone.replace(/\s+/g, ''),
        },
      })
        .then(
          (res) => {
            //验证码失败
            if (res.data.hasError) {
              vm.noTel = false
              this.$message({
                showClose: true,
                duration: 3000,
                message: '验证码发送失败',
                type: 'error',
              })
            } else {
              vm.noTel = false
            }
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '验证码发送失败',
              type: 'error',
            })
            vm.noTel = false
            vm.isCount = false
          }
        )
        .catch((error) => {
          vm.noTel = false
          vm.isCount = false
        })
    },
    //发送短信验证码
    getVscode() {
      let vm = this
      vm.noTel = true
      this.$refs.ruleForm.validateField('phone', (error) => {
        if (error) {
          //return false;
        } else {
          //验证码倒计时
          vm.isCount = true
          vm.countDownTime = 60
          vm.countDown()
          vm.sendVscode()
        }
      })
    },
    //本省企业经营地址等于注册地址
    handerChange(item) {
      if (this.ruleForm.regAddress.length > 0) {
        if (this.ruleForm.belong === '1') {
          let regAreaArray = this.$refs.regAreas.getCheckedNodes()[0].pathLabels
          if (regAreaArray.length > 1) {
            this.ruleForm.address = regAreaArray[0] + ' / ' + regAreaArray[1]
          } else {
            this.ruleForm.address = regAreaArray[0]
          }
        }
      }
    },
    //获取所属行业
    getIndustry() {
      if (this.ruleForm.industry.length > 0) {
        this.ruleForm.industry =
          this.$refs.industry.getCheckedNodes()[0].path[1]
      }
    },
    //获取注册地址的省市区
    getRegAddress() {
      let path = this.$refs.regAreas.getCheckedNodes()[0].path
      let address = this.$refs.regAreas.getCheckedNodes()[0].pathLabels
      this.regAreas.regAreaId = this.$refs.regAreas.getCheckedNodes()[0].value
    },
    //获取经营地址的市区
    getManageAddress() {
      if (this.ruleForm.belong === '1') {
        //内蒙经营地址
        this.manageAreas.bizAreaId = this.regAreas.regAreaId
      } else {
        //外省地址
        this.manageAreas.bizAreaId =
          this.$refs.manageAreas.getCheckedNodes()[0].value
      }
    },
    //图片上传
    ajaxUpload(formName, index, imgName) {
      var vm = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'post',
        dataType: 'json',
        success: function (data) {
          vm.file[index].originalName = data.name
          vm.file[index].imgId = data.id
          vm.file[index].newName = data.id + imgName
          vm.file[index].fileSize = data.size
          // vm.file[index].fileType = data.contentType;
          vm.file[index].relativePath = data.path
          vm.file[index].imgSrc = data.url
          vm.file[index].isShow = true
        },
        error: function () {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片上传失败',
            type: 'error',
          })
        },
      }
      $('#' + formName).ajaxSubmit(options)
      return false
    },
    //上传图片
    uploadImg(inputId, index, formName, imgName) {
      var vm = this
      var fileName
      var file
      var fileSize
      try {
        fileName = $('#' + inputId).val()
        file = $('#' + inputId)[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过5M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      if (fileName) {
        //判断图片类型
        if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(fileName)) {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片类型必须是jpeg，jpg，png中的一种',
            type: 'error',
          })
          $('#' + inputId).val('')
          return
        }
        //判断图片大小
        if (fileSize / 1 > 1024 * 5) {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片大小不能超过5M',
            type: 'error',
          })
          $('#' + inputId).val('')
          return
        }
        vm.ajaxUpload(formName, index, imgName)
      }
    },
    //获取图片数组
    getImg() {
      let vm = this
      const fileArray = new Array()
      for (var j = 0; j < vm.file.length; j++) {
        fileArray[j] = {
          originalName: vm.file[j].originalName,
          newName: vm.file[j].imgId + vm.file[j].newName,
          fileSize: vm.file[j].fileSize,
          fileType: vm.file[j].fileType,
          relativePath: vm.file[j].relativePath,
        }
      }
      return JSON.stringify(fileArray)
    },
    //提交表单请求
    submitRequest() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-c/companyaudit/expand/addcompany',
        data: {
          departmentType: this.companyType,
          companyType: vm.ruleForm.companyType,
          name: vm.ruleForm.companyName,
          uscc: vm.ruleForm.uscc.replace(/\s+/g, ''),
          industryId: vm.ruleForm.industry,
          belongs: vm.ruleForm.belong,
          regAreaId: vm.regAreas.regAreaId, // --注册地址全id
          bizAreaId: vm.manageAreas.bizAreaId, //   ---经营地址全id
          tel: vm.ruleForm.phone.replace(/\s+/g, ''),
          vc: vm.ruleForm.vscode,
          fileVOs: vm.getImg(),
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              vm.isRegister = false
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: res.data.errorMsg,
                type: 'error',
              })
            }
            vm.isSubmit = false
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '提交失败',
              type: 'error',
            })
            vm.isSubmit = false
          }
        )
        .catch((error) => {})
    },
    //提交申请
    submitForm(formName) {
      let vm = this
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          var isOk = 0
          for (var i = 0; i < this.file.length; i++) {
            if (!vm.file[i].imgSrc) {
              isOk++
            }
          }
          if (
            isOk > 0 &&
            (this.companyType === '0' || this.companyType === '15')
          ) {
            vm.imgRemind = '请上传三张图片'
            vm.isSubmit = false
          } else if (
            isOk > 0 &&
            isOk !== 2 &&
            (this.companyType === '5' || this.companyType === '10')
          ) {
            vm.imgRemind = '请上传登记书照片'
            vm.isSubmit = false
          } else {
            vm.imgRemind = ''
            //获取行业
            vm.getIndustry()
            //获取注册地址的省市区
            vm.getRegAddress()
            //获取经营地址的市区
            vm.getManageAddress()
            //发送请求
            vm.confirmSubmitRequest()
          }
        } else {
          vm.isSubmit = false
          return false
        }
      })
    },
    confirmSubmitRequest() {
      this.axios({
        method: 'post',
        url: 'api-c/companyaudit/base/validcompanyuscc',
        data: {
          name: this.ruleForm.companyName,
          uscc: this.ruleForm.uscc.replace(/\s+/g, ''),
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            this.submitRequest()
          } else {
            //uncredible【新华信用校验不通过】/pending【已申请未批准】/approved【已注册】
            //除了为新华校验未通过的，其他的错误应该都是不允许提交
            if (res.data.errorCode === 'uncredible') {
              this.confirmTip()
            } else {
              this.$message.error(res.data.errorMsg)
            }
          }
        })
        .catch((error) => {
          this.$message.error('企业信息校验失败，请稍后重试')
        })
    },
    confirmTip() {
      this.$confirm(
        '确定提交申请吗？当前企业名称和统一社会信用代码未通过校验，请仔细核对，确保无误',
        '提示',
        {
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning',
        }
      )
        .then(() => {
          this.submitRequest()
        })
        .catch(() => {})
    },
    //跳到注册第一步
    toRegister() {
      this.$router.push({
        path: '#/register/register',
        name: 'register',
      })
    },
    //用户注册协议
    toRegistration() {
      // this.$router.push({
      //     path: "#/common/registration",
      //     name: "registration"
      // });
      let newUrl = this.$router.resolve({
        path: '#/common/registration',
        name: 'registration',
      })
      window.open(newUrl.href, '_blank')
    },
    //信用承诺
    toCreditcommitment() {
      let newUrl = this.$router.resolve({
        path: '#/common/creditCommitment',
        name: 'creditCommitment',
      })
      window.open(newUrl.href, '_blank')
    },
    validUsccAndCompany(companyName, uscc) {
      if (companyName && uscc) {
        this.axios({
          method: 'post',
          url: 'api-c/companyaudit/base/validcompanybyproject',
          data: {
            name: companyName.replace(/\s+/g, ''),
            uscc: uscc.replace(/\s+/g, ''),
          },
        })
          .then((res) => {
            if (!res.data.hasError) {
              this.$message({
                message: '已通过校验',
                type: 'success',
              })
            } else {
              if (res.data.errorCode == 'unmatched') {
                this.$message({
                  message: '未通过校验，请确认信息是否准确',
                  type: 'warning',
                })
              }
            }
          })
          .catch((error) => {
            this.$message.error('验证失败')
          })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  position: relative;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  .boxWrap {
    background: #f2f4f6;
    position: fixed;
    top: 0;
    left: 0;
    right: -17px;
    bottom: 0;
    background-size: 100% 100%;
    overflow-y: auto;
    .mainBox {
      width: 980px;
      background-color: #fff;
      margin: 0 auto;
      border-radius: 10px;
      margin-bottom: 35px;
      padding: 60px;
      text-align: center;
      position: relative;
      // 提示语
      .reminder {
        text-align: left;
        color: #ff4242;
        font-size: 14px;
        background: #fffbe6;
        border-radius: 3px;
        padding: 0 30px;
        height: 48px;
        line-height: 48px;
        border-radius: 10px 10px 0 0;
        i {
          color: #ffaa00;
          font-size: 20px;
          vertical-align: -2px;
        }
      }
      .formTop {
        color: #666;
        font-size: 14px;
        margin-bottom: 30px;
        .applyTitle {
          margin-top: 35px;
          font-size: 28px;
          color: #333333;
          font-weight: bold;
        }
        .loginLink {
          position: static;
          text-align: right;
          margin: 0 30px;
          padding: 24px 0 16px 0;
          border-bottom: 1px solid #d5dee7;
          .toLogin {
            color: #409eff;
            cursor: pointer;
          }
        }
      }
      .ruleForm {
        width: 510px;
        display: inline-block;
        /deep/ .el-form-item__content {
          text-align: left;
        }
        .el-select {
          width: 100%;
        }
        .industrySelect {
          width: 361px;
        }
        .areasSelect {
          width: 361px;
        }
        .vscodeInput {
          .el-input {
            width: 209px;
          }
          .vscodeBtn {
            width: 128px;
            border: 1px solid #009588;
            color: #009588;
            margin-left: 19px;
          }
        }
        .radioBox /deep/.el-form-item__content {
          text-align: left;
        }
        /deep/.imgLabel {
          label:before {
            content: '*';
            color: #f56c6c;
            margin-right: 4px;
          }
          .imgRemind {
            color: #f56c6c;
            font-size: 12px;
            line-height: 1;
          }
        }
      }
      .registerBtn {
        margin-top: 0px;
      }
      .suceesRemind {
        font-size: 28px;
        color: #009588;
        margin: 30px 0px 0px;
      }
      .el-dialog img {
        width: 100%;
      }
    }
    .alignCenter {
      text-align: center;
    }
    .registered {
      text-align: center;
      padding: 50px 100px;
      margin-top: 5%;
      .suceesRemind {
        font-size: 28px;
        color: #009588;
        margin: 30px 0px 0px;
      }
      .messageRemind {
        margin-bottom: 25px;
        color: #666;
        font-size: 14px;
        margin-top: 20px;
      }
    }
  }
  //上传图片样式
  .imgBoxs {
    .imgBox {
      text-align: center;
      float: left;
      margin-right: 15px;
      font-size: 12px;
      .imgTopBox {
        width: 104px;
        height: 104px;
        border: 1px dotted #d4dae6;
        position: relative;
        background-color: #f5f7fb;
        .uploadBtn {
          width: 102px;
          height: 73px;
          cursor: pointer;
          input {
            opacity: 0;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 100;
            height: 74px;
            width: 104px;
          }
          i {
            line-height: 74px;
            font-size: 25px;
            color: #b5b6b7;
          }
          img {
            width: 102px;
            height: 73px;
            position: absolute;
            top: 0;
            left: 0;
          }
        }
        .imgName {
          height: 30px;
          line-height: 30px;
          background: rgba(206, 206, 206, 0.3);
          color: #aaa;
        }
      }
    }
  }
  /deep/.el-dialog__body {
    max-height: fit-content;
    text-align: center;
  }
}

.container .boxWrap .registerMainBox {
  padding: 0;
}
.boxWrap /deep/ .topTitleBox {
  background: url('../../../static/img/loginImg/headerBG.png') no-repeat;
  background-size: 100% 100%;
  margin-bottom: 30px;
}
.contarctBorderBottom {
  margin: 20px 0 5px 0;
}
.contarctTopBorder {
  margin: 0 30px;
  position: absolute;
  width: calc(100% - 60px);
  height: 1px;
  background: #d5dee7;
  bottom: 150px;
}
.el-button {
  margin-left: 0;
}
.contract {
  cursor: pointer;
  color: #409eff;
}

/deep/.el-form-item__label {
  color: #333333;
}
</style>
